<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <title>使用IIFE提升性能</title>
  </head>
  <body>
    <button>点击添加事件</button>
    <script>
      /**
       * 原始方式：根据浏览器环境添加事件监听
       * @param {Element} ele 元素
       * @param {string} eventName 事件名
       * @param {Function} handler 监听函数
       */
      /* function addEvent(ele, eventName, handler) {
        if (ele.addEventListener) {
          ele.addEventListener(eventName, handler);
        } else if (ele.attachEvent) {
          ele.attachEvent("on" + eventName, handler);
        } else {
          ele["on" + eventName] = handler;
        }
      } */

      /**
       * 使用IFFE优化
       */
      const addEvent = (function () {
        if (window.addEventListener) {
          return function (ele, eventName, handler) {
            ele.addEventListener(eventName, handler);
          };
        } else if (window.attachEvent) {
          return function (ele, eventName, handler) {
            ele.attachEvent("on" + eventName, handler);
          };
        } else {
          return function (ele, eventName, handler) {
            ele["on" + eventName] = handler;
          };
        }
      })();

      // 测试
      const btn = document.querySelector("button");
      addEvent(btn, "click", function (ev) {
        console.dir(ev.target);
      });
    </script>
  </body>
</html>
